// 个人信息设置页面逻辑（资料扩展版）
// 设计补充：
// 1. 支持扩展字段：real_name, gender, birth_date, address, email, nickname, avatar。
// 2. gender 采用内部枚举映射：['male','female','other'] ⇄ ['男','女','其他']。
// 3. 仅提交发生变化的字段，减少无效 PUT；头像单独先上传，得到 URL 后一起写。
// 4. 兼容后端：假设后端统一接收 PUT /user/profile JSON 字段名与上述一致；若后端命名不同可在 buildUpdatePayload 里集中适配。
// 5. 修复原文件中直接调用未引用命名空间方法 (getUserProfile / getToken) 的问题，改用 auth.*。

const auth = require('../../utils/auth');
const config = require('../../utils/config'); // 可能后续使用到全局配置，保留
const { buildMediaUrl } = require('../../utils/media');

const app = getApp();

Page({
  data: {
    userInfo: {
      username: '',
      phone: '',
      avatar: '',
      nickname: '',
      real_name: '',
      gender: '',        // 后端值: male|female|other (或空)
      birth_date: '',    // YYYY-MM-DD
      address: '',
      email: '',
      wechat_bound: false
    },
  originalUserInfo: null,  // 备份用于差异检测 (avatar 存相对路径)
    tempAvatarUrl: '',
  displayAvatar: '',       // 仅用于展示的绝对URL
    genderOptions: ['男','女','其他'],
    genderMap: { '男': 'male', '女': 'female', '其他': 'other' },
    genderReverseMap: { 'male': '男', 'female': '女', 'other': '其他' },
    genderIndex: -1,
    loading: false,
    saving: false
  },

  onLoad() {
    this.loadUserInfo();
  },

  /**
   * 加载用户信息
   */
  async loadUserInfo() {
    try {
      this.setData({ loading: true });
      let userInfo = null;
      try {
        // 优先调用后端新接口
        const token = auth.getToken();
        if (token) {
          const res = await new Promise((resolve, reject) => {
            wx.request({
              url: `${app.globalData.apiBaseUrl}/user/profile`,
              method: 'GET',
              header: { 'Authorization': `Bearer ${token}` },
              success: resolve,
              fail: reject
            });
          });
          if (res.statusCode === 200 && res.data.success) {
            userInfo = res.data.data;
          } else {
            userInfo = await auth.getUserProfile();
          }
        } else {
          userInfo = await auth.getUserProfile();
        }
      } catch (e) {
        userInfo = wx.getStorageSync('userInfo') || null;
      }
      if (!userInfo) return;
  const normalized = {
  username: userInfo.username || '',
  // phone 优先使用后端返回的 mobile；若无则检测 username 是否看似手机号
  phone: userInfo.mobile || userInfo.phone || (/^\d{6,15}$/.test(userInfo.username || '') ? userInfo.username : ''),
  avatar: userInfo.avatar || userInfo.avatar_url || '',
        nickname: userInfo.nickname || userInfo.username || '',
        real_name: userInfo.real_name || userInfo.realName || '',
        gender: userInfo.gender || '',
        birth_date: userInfo.birth_date || userInfo.birthDate || '',
        address: userInfo.address || '',
        email: userInfo.email || '',
        wechat_bound: !!(userInfo.wechat_bound || userInfo.wechat_openid || userInfo.wechatUnionId)
      };
      // 计算 genderIndex
      const genderIndex = normalized.gender ? this.data.genderOptions.indexOf(this.data.genderReverseMap[normalized.gender] || '') : -1;
  const displayAvatar = buildMediaUrl(normalized.avatar);
  this.setData({ userInfo: normalized, originalUserInfo: { ...normalized }, genderIndex, displayAvatar });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 选择头像
   */
  chooseAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({ tempAvatarUrl: tempFilePath });
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
        wx.showToast({
          title: '选择图片失败',
          icon: 'error'
        });
      }
    });
  },

  /**
   * 昵称输入
   */
  onNicknameInput(e) { this.setData({ 'userInfo.nickname': e.detail.value }); },
  onRealNameInput(e) { this.setData({ 'userInfo.real_name': e.detail.value }); },
  onAddressInput(e) { this.setData({ 'userInfo.address': e.detail.value }); },
  onEmailInput(e) { this.setData({ 'userInfo.email': e.detail.value }); },
  onGenderChange(e) {
    try {
      const index = Number(e.detail.value);
      if (isNaN(index) || index < 0 || index >= this.data.genderOptions.length) return;
      const label = this.data.genderOptions[index];
      const value = this.data.genderMap[label];
      if (!value) return;
      this.setData({ genderIndex: index, 'userInfo.gender': value });
    } catch (err) {
      console.warn('性别选择处理异常', err);
    }
  },
  onBirthDateChange(e) { this.setData({ 'userInfo.birth_date': e.detail.value }); },

  onBindWeChat() {
    if (this.data.userInfo.wechat_bound) return;
    // 使用 wx.login 获取 code，调用后端 /user/wechat_bind (模拟实现) 完成绑定
    wx.login({
      success: (resp) => {
        if (!resp.code) {
          wx.showToast({ title: '获取code失败', icon: 'error' });
          return;
        }
        const token = auth.getToken();
        if (!token) {
          wx.showToast({ title: '未登录', icon: 'error' });
          return;
        }
        wx.request({
          url: `${app.globalData.apiBaseUrl}/user/wechat_bind`,
          method: 'POST',
          header: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
          data: { code: resp.code },
          success: (r) => {
            if (r.statusCode === 200 && r.data && r.data.success) {
              const openid = (r.data.data && r.data.data.openid) || '';
              const updated = { ...this.data.userInfo, wechat_bound: true, wechat_openid: openid };
              this.setData({ userInfo: updated });
              const cached = wx.getStorageSync('userInfo') || {};
              wx.setStorageSync('userInfo', { ...cached, wechat_bound: true, wechat_openid: openid });
              wx.showToast({ title: '绑定成功', icon: 'success' });
            } else {
              wx.showToast({ title: (r.data && r.data.message) || '绑定失败', icon: 'error' });
            }
          },
          fail: () => wx.showToast({ title: '请求失败', icon: 'error' })
        });
      },
      fail: () => wx.showToast({ title: 'wx.login失败', icon: 'error' })
    });
  },

  onUnbindWeChat() {
    if (!this.data.userInfo.wechat_bound) return;
    wx.showModal({
      title: '解绑确认',
      content: '解绑后可重新绑定其他微信账号，确认解绑？',
      confirmColor: '#ff4d4f',
      success: (r) => {
        if (!r.confirm) return;
        const token = auth.getToken();
        if (!token) {
          wx.showToast({ title: '未登录', icon: 'error' });
          return;
        }
        wx.request({
          url: `${app.globalData.apiBaseUrl}/user/unbind_wechat`,
          method: 'POST',
          header: { 'Authorization': `Bearer ${token}` },
          success: (res) => {
            if (res.statusCode === 200 && res.data && res.data.success) {
              const updated = { ...this.data.userInfo, wechat_bound: false, wechat_openid: '' };
              this.setData({ userInfo: updated });
              const cached = wx.getStorageSync('userInfo') || {};
              wx.setStorageSync('userInfo', { ...cached, wechat_bound: false, wechat_openid: '' });
              wx.showToast({ title: '已解绑', icon: 'success' });
            } else {
              wx.showToast({ title: (res.data && res.data.message) || '解绑失败', icon: 'error' });
            }
          },
          fail: () => wx.showToast({ title: '请求失败', icon: 'error' })
        });
      }
    });
  },

  bindMobile() {
    const { phone } = this.data.userInfo;
    if (phone) return; // 已有手机号不重复绑定
    wx.showModal({
      title: '绑定手机号',
      editable: true,
      placeholderText: '输入手机号',
      success: async (res) => {
        if (res.confirm && res.content) {
          const mobile = res.content.trim();
          if (!/^\d{6,15}$/.test(mobile)) {
            wx.showToast({ title: '格式不正确', icon: 'error' });
            return;
          }
          try {
            const token = auth.getToken();
            const resp = await new Promise((resolve, reject) => {
              wx.request({
                url: `${app.globalData.apiBaseUrl}/user/bind_mobile`,
                method: 'POST',
                header: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
                data: { mobile },
                success: resolve,
                fail: reject
              });
            });
            if (resp.statusCode === 200 && resp.data.success) {
              this.setData({ 'userInfo.phone': mobile, originalUserInfo: { ...this.data.originalUserInfo, phone: mobile } });
              wx.showToast({ title: '绑定成功', icon: 'success' });
            } else {
              wx.showToast({ title: resp.data.message || '绑定失败', icon: 'error' });
            }
          } catch (e) {
            wx.showToast({ title: '请求失败', icon: 'error' });
          }
        }
      }
    });
  },

  /**
   * 构建需要提交给后端的变更字段（差异检测）
   */
  buildUpdatePayload(current, original) {
    if (!original) return current;
    const fields = ['nickname','real_name','gender','birth_date','address','email','avatar'];
    const payload = {};
    fields.forEach(f => {
      if (current[f] !== undefined && current[f] !== original[f]) {
        payload[f] = current[f];
      }
    });
    return payload;
  },

  /** 简单校验 */
  validateForm(userInfo) {
    if (!userInfo.nickname.trim()) return '请输入昵称';
    if (userInfo.email) {
      const emailRegex = /^[\w.-]+@[\w.-]+\.[A-Za-z]{2,}$/;
      if (!emailRegex.test(userInfo.email)) return '邮箱格式不正确';
    }
    if (userInfo.birth_date) {
      const today = new Date();
      const birth = new Date(userInfo.birth_date);
      if (birth > today) return '出生日期不能是未来';
    }
    return null;
  },

  /**
   * 保存个人信息
   */
  async saveProfile() {
    if (this.data.saving) return;
    const { userInfo, tempAvatarUrl, originalUserInfo } = this.data;

    const errMsg = this.validateForm(userInfo);
    if (errMsg) {
      wx.showToast({ title: errMsg, icon: 'error' });
      return;
    }

    try {
      this.setData({ saving: true });
      wx.showLoading({ title: '保存中...' });

      const token = auth.getToken();
      if (!token) throw new Error('请先登录');

      let avatarUrl = userInfo.avatar; // 相对路径
      if (tempAvatarUrl) {
        avatarUrl = await this.uploadAvatar(tempAvatarUrl);
        this.setData({ 'userInfo.avatar': avatarUrl, displayAvatar: buildMediaUrl(avatarUrl) });
      }

      const payload = this.buildUpdatePayload({ ...this.data.userInfo, avatar: avatarUrl }, originalUserInfo);
      if (Object.keys(payload).length === 0) {
        wx.hideLoading();
        wx.showToast({ title: '无改动', icon: 'none' });
        return;
      }

      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/user/profile`,
          method: 'PUT',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: payload,
          success: resolve,
          fail: reject
        });
      });

      if (response.statusCode === 200 && response.data.success) {
        // 合并更新本地缓存 & originalUserInfo
        const localUserInfo = wx.getStorageSync('userInfo') || {};
  const updatedUserInfo = { ...localUserInfo, ...payload };
        wx.setStorageSync('userInfo', updatedUserInfo);
  // originalUserInfo 保持相对路径存储
  this.setData({ originalUserInfo: { ...this.data.originalUserInfo, ...payload }, tempAvatarUrl: '' });
        wx.hideLoading();
        wx.showToast({ title: '保存成功', icon: 'success' });
        setTimeout(() => { wx.navigateBack(); }, 1200);
      } else {
        throw new Error(response.data.message || '保存失败');
      }
    } catch (error) {
      wx.hideLoading();
      console.error('保存个人信息失败:', error);
      wx.showToast({ title: error.message || '保存失败', icon: 'error' });
    } finally {
      this.setData({ saving: false });
    }
  },

  /**
   * 上传头像
   */
  async uploadAvatar(filePath) {
    return new Promise((resolve, reject) => {
      const token = auth.getToken();
      wx.uploadFile({
        url: `${app.globalData.apiBaseUrl}/upload/image?category=avatar`,
        filePath,
        name: 'image',
        formData: { category: 'avatar' },
        header: { 'Authorization': `Bearer ${token}` },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.success) {
              // 返回相对URL，保持统一，再由展示层拼接
              resolve(data.data.url); // 相对路径 /media/image/avatar/...
            } else reject(new Error(data.message || '上传失败'));
          } catch (e) { reject(new Error('上传响应解析失败')); }
        },
        fail: () => reject(new Error('上传请求失败'))
      });
    });
  }
});
